import html2canvas from '@/static/js/html2canvas.min.js'
import {
	Base64toUrl
} from '@/api/index.js';
export const CanvasMixins = {
	data() {
		return {}
	},
	methods: {
		// h5保存图片
		htmlSave() {
			uni.showLoading({
				title: '图片正在生成中'
			})
			console.log('htmlSave')
			const dom = document.querySelector('#swiper')
			html2canvas(dom, {
				width: dom.clientWidth,
				height: dom.scrollHeight,
				scrollY: 0,
				scrollX: 0,
				useCORS: true,
				// allowTaint: true
			}).then((canvas) => {
				const base64 = canvas.toDataURL('image/jpg')
				this.postBase64(base64)
			})
		},
		//将Base64传入后台转换成url
		postBase64(base64) {
			const _this = this
			Base64toUrl({
				content: JSON.stringify(base64),
				suffix: ".jpg"
			}).then(urlRes => {
				uni.hideLoading()
				console.log(urlRes)
				var link = document.createElement('a');
				//把a标签的href属性赋值到生成好了的url
				// link.href = dres.tempFilePath;
				link.href = urlRes.data.url;
				//通过a标签的download属性修改下载图片的名字
				link.title = _this.innerData.realName + (new Date().getTime()) + '.jpg';
				link.download = (new Date().getTime()) + '.jpg';
				// link.download = _this.innerData.realName + (new Date().getTime()) + '.jpg';
				//让a标签的click函数，直接下载图片
				link.click();
			})
		},
		// 小程序画图保存图片
		async wxSave(obj) {
			uni.showLoading({
				title: '图片正在生成中'
			})
			try {

				const _this = this
				const item = this.innerData
				let ctx = uni.createCanvasContext('firstCanvas', this);
				ctx.fillStyle = '#fff';
				// 530rpx 944rpx
				ctx.fillRect(0, 0, 530, 944);
				let head = null
				let videoImg = null
				if (item.dataHumanSucceedImage && this.active == 0) {
					videoImg = (await uni.getImageInfo({
						src: item.dataHumanSucceedImage
					}))[1].path
					ctx.drawImage(videoImg, 0, 0, 530, 556);
					head = (await uni.getImageInfo({
						src: 'https://ebc-prod.cdn.benwunet.com/uni-static/activity-year/video-bg.png'
					}))[1].path
				} else {
					head = (await uni.getImageInfo({
						src: item.posterBackgroundUrl[this.active]
					}))[1].path
				}
				const avatar = (await uni.getImageInfo({
					src: item.avatar || item.imagePhoto
				}))[1].path
				const avatarRadius = (await uni.getImageInfo({
					src: 'https://ebc-prod.cdn.benwunet.com/uni-static/avatar-radius.png'
				}))[1].path
				if (item.codeUrl) {
					const code = (await uni.getImageInfo({
						src: item.codeUrl
					}))[1].path
					ctx.drawImage(code, 390, 790, 120, 120);
				}
				ctx.drawImage(head, 0, 0, 530, 756);
				console.log('path========', head, avatar)
				if (this.active == 3) {
					// this.drawText('产品我们要做到专业化、行业化、品牌化。', 24, 265,7, 14, 14, '#720800', ctx)
					// this.drawText('康德教育', 26, 280, 1, 14, '#720800', ctx)
					const nameLength = item.realName.length
					if (nameLength >= 4) {
						this.drawText(item.realName, 52, 560, 1, 28, '#720800', ctx)
					} else if (nameLength == 3) {
						this.drawText(item.realName, 52, 580, 1, 28, '#720800', ctx)
					} else if (nameLength == 2) {
						this.drawText(item.realName, 52, 600, 1, 28, '#720800', ctx)
					} else if (nameLength == 1) {
						this.drawText(item.realName, 52, 620, 1, 28, '#720800', ctx)
					}
					ctx.stroke()
				}
				ctx.drawImage(avatar, 30, 800, 100, 100);
				ctx.drawImage(avatarRadius, 10, 780, 140, 140);
				ctx.fillStyle = '#0F0400';
				ctx.setFontSize(32)
				ctx.fillText(item.realName, 150, 830)
				ctx.stroke()
				ctx.fillStyle = '#969699';
				ctx.setFontSize(20)
				ctx.fillText(item.firstCompanyName || item.industry, 150, 864)
				ctx.stroke()
				ctx.fillStyle = '#666564';
				ctx.setFontSize(20)
				ctx.fillText(item.firstPositionName || '自由职位', 150, 890)
				ctx.stroke()
				// ctx.drawImage(logo, 220, 420, 10, 10);
				ctx.draw(true, (ret) => { // draw方法 把以上内容画到 canvas 中。
					console.log('draw', ret)
					uni.hideLoading()
					uni.canvasToTempFilePath({ // 保存canvas为图片
						canvasId: 'firstCanvas',
						fileType: 'jpg',
						width: 530, //分享图片尺寸=画布尺寸1*缩放比0.5*像素比2
						height: 944,
						// destWidth: 530, //分享图片尺寸=画布尺寸1*缩放比0.5*像素比2
						//                destHeight: 944,
						complete: function(res) {
							console.log('firstCanvas == tempFilePath', res.tempFilePath)
							if (!res.tempFilePath) {
								uni.showToast({
									title: '图片未生成',
									icon: 'none'
								})
								uni.hideLoading()
								return;
							}
							_this.authSavePosterPath(res.tempFilePath)
						}
					}, this)
				});

			} catch (err) {
				console.log(err)
				uni.showToast({
					title: '图片未生成',
					icon: 'none'
				})
				uni.hideLoading()
			}
		},
		// 保存图片到相册
		base64DownloadFile(content) {
			uni.saveImageToPhotosAlbum({
				filePath: content,
				success: function(res2) {
					uni.showToast({
						title: '保存成功',
						icon: "none",
						duration: 5000
					})
				},
				fail: function(err) {
					// console.log(err.errMsg);
				}
			})
		},
		// 获取保存到相册的权限
		authSavePosterPath(base64) {
			//获取用户的当前设置。获取相册权限
			uni.getSetting({
				success: (res) => {
					//如果没有相册权限
					if (!res.authSetting["scope.writePhotosAlbum"]) {
						//向用户发起授权请求
						uni.authorize({
							scope: "scope.writePhotosAlbum",
							success: () => {
								//授权成功保存图片到系统相册
								this.base64DownloadFile(base64)
							},
							//授权失败
							fail: () => {
								uni.showModal({
									title: "您已拒绝获取相册权限",
									content: "是否进入权限管理，调整授权？",
									success: (res) => {
										if (res.confirm) {
											//调起客户端小程序设置界面，返回用户设置的操作结果。（重新让用户授权）
											uni.openSetting({
												success: (res) => {
													console.log(res
														.authSetting
														);
												},
											});
										} else if (res.cancel) {
											return uni.showToast({
												title: "已取消！",
											});
										}
									},
								});
							},
						});
					} else {
						//如果已有相册权限，直接保存图片到系统相册
						this.base64DownloadFile(base64)
					}
				},
				fail: (res) => {},
			});
		},
		// 保存base64的图片
		saveImageToPhotosAlbum(base) {
			let base64 = base.replace(/^data:image\/\w+;base64,/, ""); //去掉data:image/png;base64,
			let filePath = wx.env.USER_DATA_PATH + '/hym_pay_qrcode' + new Date().getTime() + '.png';
			uni.getFileSystemManager().writeFile({
				filePath: filePath, //创建一个临时文件名
				data: base64, //写入的文本或二进制数据
				encoding: 'base64', //写入当前文件的字符编码
				success: res => {
					this.base64DownloadFile(filePath)
				},
				fail: err => {
					//console.log(err)
				}
			})
		},
		// 画字
		drawText(text, x, y, num, fs, color, ctx) {
			// 1 将字符串转换成数组
			let test = text.split("")
			let row = []
			// // 1.1 设置样式
			ctx.setFontSize(fs)
			ctx.fillStyle = color
			// 1.2 计算文字宽度，若文字宽度大于设定的宽度，则push到数组下一个元素，否则将字符串++
			for (let i = 0; i < test.length; i++) {
				const a = text.substring(i, i + num);
				row.push(a)
				i = (i + num) - 1
			}
			// 1.4 遍历数组,输出文字
			for (let j = 0; j < row.length; j++) {
				ctx.fillText(row[j], x, y + ((j * 1.3) * fs))
				// ctx.fillText( row[j], x, y+(j+1) * fs + fs)
			}
			ctx.stroke()
		},
	}
}
